<template>
  <view class="container">
    <view class="progress-container">
      <view class="progress-bar">
        <view class="progress" :style="{ width: `${progress}%` }" />
      </view>
      <text class="progress-text">{{ progress }}%</text>
    </view>

    <view class="question-container" v-if="!showResult">
      <view class="question-card">
        <view class="question-number">问题 {{ currentQuestion + 1 }}/{{ questions.length }}</view>
        <view class="question-content">{{ questions[currentQuestion].question }}</view>

        <view v-if="questions[currentQuestion].type == 'input'" class="input-answer">
          <input type="text" v-model="inputAnswer" :placeholder="'请输入您的答案'" class="answer-input" />
        </view>

        <view v-else-if="questions[currentQuestion].type == 'choice'" class="options">
          <view v-for="(option, index) in questions[currentQuestion].options" :key="index" class="option"
            :class="{ selected: selectedOption === index }" @click="selectOption(index)">
            <view class="option-circle">{{ ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'][index] }}</view>
            <text>{{ option }}</text>
          </view>
        </view>
      </view>

      <button class="next-btn" :class="{ active: isCurrentQuestionAnswered }" :disabled="!isCurrentQuestionAnswered"
        @click="nextQuestion">
        {{ currentQuestion === questions.length - 1 ? '查看结果' : '下一题' }}
      </button>
    </view>


  </view>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import request from '../../utils/request';

const inputAnswer = ref('')
const questions = ref([])

// 当前问题序号
const currentQuestion = ref(0)
// 当前问题选项
const selectedOption = ref(null)
// 是否显示结果
const showResult = ref(false)
// 已回答问题数量
const answeredQuestions = ref(0)
// 已回答问题+答案
const answers = ref([])
const requestData = ref({})

onMounted(async () => {
  uni.showLoading({
    title: "加载中"
  })
  try {
    const res = await request.get('/questions')
    res.data.map(item => {
      questions.value.push({
        type: item.type,
        question: item.content,
        options: item.type === 'choice' ? JSON.parse(item.options) : null
      })
    })

    // 获取 tongue的五个特征
    requestData.value.tongueDiagnosisId = uni.getStorageSync('tongueDescription').id;
    uni.removeStorageSync('tongueDescription')
  } catch (error) {
    uni.showToast({
      title: error || '获取问题失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
})

const progress = computed(() => {
  return Math.round((answeredQuestions.value / questions.value.length) * 100)
})

const selectOption = (index) => {
  selectedOption.value = index
}

// 修改计算属性判断当前问题是否已回答
const isCurrentQuestionAnswered = computed(() => {
  const currentQ = questions.value[currentQuestion.value]
  if (currentQ.type === 'input') {
    return inputAnswer.value.trim() !== ''
  } else if (currentQ.type === 'choice') {
    return selectedOption.value != null
  }
  return false
})

// 修改 nextQuestion 函数
const nextQuestion = () => {
  if (currentQuestion.value < questions.value.length - 1) {
    // 保存答案
    const currentQ = questions.value[currentQuestion.value]
    let answer
    if (currentQ.type === 'input') {
      answer = inputAnswer.value
    } else if (currentQ.type === 'choice') {
      answer = currentQ.options[selectedOption.value]
    }

    answers.value.push({
      question: currentQ.question,
      answer: answer
    })

    currentQuestion.value++
    answeredQuestions.value++

    // 重置选项
    selectedOption.value = null
    inputAnswer.value = ''
  } else {
    // 保存最后一个问题的答案
    const currentQ = questions.value[currentQuestion.value]
    let answer
    if (currentQ.type === 'input') {
      answer = inputAnswer.value
    } else if (currentQ.type === 'choice') {
      answer = currentQ.options[selectedOption.value]
    }

    answers.value.push({
      question: currentQ.question,
      answer: answer
    })

    // 输出答案
    getResult()
    answeredQuestions.value = questions.value.length
  }
}

const getResult = async () => {
  // 显示加载提示
  uni.showLoading({
    title: '正在分析...',
    mask: true,
  })

  try {
    requestData.value.answers = answers.value
    const result = await request.post('/evaluate/result', requestData.value)
    // 隐藏加载提示
    uni.hideLoading()
    uni.showToast({
      title: '评估结果已保存',
      icon: 'success',
      duration: 3000
    })

    uni.setStorageSync("evaluateResult", result.data);

    // 跳转到结果页面并传递数据
    uni.reLaunch({
      url: '/pages/question/result'
    })
  } catch (error) {
    // 发生错误时也要隐藏加载提示
    uni.hideLoading()
    uni.showToast({
      title: error || '获取结果失败',
      icon: 'none'
    })
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
  padding: 40rpx 30rpx;
}

.progress-container {
  margin-bottom: 40rpx;

  .progress-bar {
    height: 8rpx;
    background: rgba(0, 122, 255, 0.1);
    border-radius: 4rpx;
    overflow: hidden;

    .progress {
      height: 100%;
      background: linear-gradient(90deg, #007AFF, #00C6FF);
      transition: width 0.5s ease;
    }
  }

  .progress-text {
    font-size: 24rpx;
    color: #007AFF;
    margin-top: 10rpx;
  }
}

.question-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.05);

  .question-number {
    font-size: 28rpx;
    color: #007AFF;
    margin-bottom: 20rpx;
  }

  .question-content {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 60rpx;
  }
}

.input-answer {
  margin: 20rpx 0;

  .answer-input {
    background: #f8f9fa;
    padding: 20rpx;
    border-radius: 15rpx;
    width: 100%;
    box-sizing: border-box;
    font-size: 32rpx;
    min-height: 90rpx;
    line-height: 1.5;
  }
}

.options {
  .option {
    display: flex;
    align-items: center;
    background: #f8f9fa;
    padding: 30rpx;
    border-radius: 15rpx;
    margin-bottom: 20rpx;
    transition: all 0.3s;

    &.selected {
      background: rgba(0, 122, 255, 0.1);
      border: 2rpx solid #007AFF;

      .option-circle {
        background: #007AFF;
        color: #fff;
      }
    }

    .option-circle {
      width: 60rpx;
      height: 60rpx;
      border-radius: 30rpx;
      background: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
      font-size: 28rpx;
      color: #666;
      border: 2rpx solid #ddd;
    }
  }
}

.next-btn {
  margin-top: 60rpx;
  background: #007AFF;
  color: #fff;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 44rpx;
  font-size: 32rpx;

  &:disabled {
    opacity: 0.5;
  }
}
</style>